package com.ylkj.patient.ui.activities.webview;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.PermissionChecker;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.ProjectConfigure;
import com.examination.mlib.constants.UserInfoConstants;
import com.examination.mlib.baseold.ModuleBaseActivity;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableMap;
import com.google.gson.Gson;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.ToastUtils;
import com.ylkj.patient.MainApplication;
import com.ylkj.patient.R;
import com.ylkj.patient.utils.AppReactUtils;
import com.ylkj.patient.utils.PushMessageUtil;
import com.ylkj.patient.utils.WXShareUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.function.BinaryOperator;

import crossoverone.statuslib.StatusUtil;

@Route(path = ARouterConstants.MineWebviewActivity)
public class MineWebViewActivity extends ModuleBaseActivity {

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10001;
    private View webBack;
    private LinearLayout webClose;
    //    private ImageView webClose;
    private TextView webviewtitle;
    private WebView downloadBoring;
    private View webShareView;
    @Autowired
    String title;
    @Autowired
    String url;
    @Autowired
    String rnTypeWeb; //Channel-XXXIANGRONG
    @Autowired
    boolean ishtml;
    @Autowired
    boolean isNotReloadOnRestart;
    @Autowired
    boolean isNotReceivedTitle;
    @Autowired
    boolean isShowLoading;


    @Override
    public int bondLayout() {
        return R.layout.activity_web_view;
    }

    @Override
    public void initView() {
        LoadingUtils.getLoadingUtils(this).showLoading();
        ARouter.getInstance().inject(this);   //注入
        //状态栏修改
        StatusUtil.setUseStatusBarColor(this, Color.WHITE);
        StatusUtil.setSystemStatus(this, false, true);
        webBack = findViewById(R.id.web_back);
        webShareView = findViewById(R.id.web_share);
        webClose = findViewById(R.id.web_close);
        webviewtitle = findViewById(R.id.webviewtitle);
        downloadBoring = findViewById(R.id.download_boring);
//        webClose = (ImageView) findViewById(R.id.web_close);

        downloadBoring.addJavascriptInterface(new WebJavascriptInterface(this), "WebJavascriptInterface");
        downloadBoring.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        /* 设置支持Js,必须设置的,基本大多数网页都涉及js */
        downloadBoring.getSettings().setJavaScriptEnabled(true);
        /* 设置为使用webview推荐的窗口，主要是为了配合下一个属性 */
        downloadBoring.getSettings().setUseWideViewPort(false);
        /* 设置网页自适应屏幕大小，该属性必须和上一属性配合使用 */
        downloadBoring.getSettings().setLoadWithOverviewMode(true);

        downloadBoring.setWebViewClient(new ArticleWebViewClient());
        downloadBoring.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
//                if (isReceivedTitle && !TextUtils.isEmpty(title)) {
                ALog.e("webviewTitle", "receivedTitle:" + ishtml + " " + isNotReceivedTitle + " " + title);
                if (!isNotReceivedTitle && !ishtml && !TextUtils.isEmpty(title) && !title.startsWith("http") && !title.contains(":") && !title.contains("blank")) {
                    ALog.e("receivedTitle", "title: " + title);
                    webviewtitle.setText(title);
                    MineWebViewActivity.this.title = title;
                }
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });
//        downloadBoring.setWebViewClient(new WebViewClient(){
//
//            @Override
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                super.onPageStarted(view, url, favicon);
//                if (downloadBoring.canGoBack()){
//                    webClose.setVisibility(View.VISIBLE);
//                }else{
//                    webClose.setVisibility(View.GONE);
//                }
//            }
//
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//                if (downloadBoring.canGoBack()){
//                    webClose.setVisibility(View.VISIBLE);
//                }else{
//                    webClose.setVisibility(View.GONE);
//                }
//            }
//        });

        downloadBoring.getSettings().setTextZoom(100);
        downloadBoring.getSettings().setAllowFileAccess(true);
        downloadBoring.getSettings().setDomStorageEnabled(true);
        downloadBoring.getSettings().setBlockNetworkImage(false);
        downloadBoring.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        downloadBoring.getSettings().setLoadsImagesAutomatically(true);
        downloadBoring.getSettings().setSupportMultipleWindows(false);
//        配置webview保存密码选项
        downloadBoring.getSettings().setSavePassword(false);
        if (!TextUtils.isEmpty(rnTypeWeb) && rnTypeWeb.equals("Channel-XXXIANGRONG")) {

        } else {
            String userAgentString = downloadBoring.getSettings().getUserAgentString();
            String IVversion = " IV." + DevicesUtils.getVersionName();
            userAgentString = userAgentString + " MicroMessenger/4.5.255" + " " + ProjectConfigure.WebView_UserAgent;
            downloadBoring.getSettings().setUserAgentString(userAgentString + IVversion);
        }
        downloadBoring.getSettings().setMediaPlaybackRequiresUserGesture(false);
        /* 设置是否允许webview使用缩放的功能 */
        //让缩放显示的最小值为起始
//        downloadBoring.setInitialScale(100);
        downloadBoring.getSettings().setBuiltInZoomControls(true);
        downloadBoring.getSettings().setDisplayZoomControls(false); //隐藏webview缩放按钮
        webviewtitle.setText(title);
        if (url.contains("covid-home")) {
            webShareView.setVisibility(View.VISIBLE);
        } else {
            webShareView.setVisibility(View.INVISIBLE);
        }

        if (ishtml) {
            downloadBoring.loadDataWithBaseURL(null, url, "text/html", "UTF-8", null);
        } else {
            //https://activity-spare.yilijk.com/index.html?t=${timestamp}#/cms/88?tk=${token}
            if (url.contains("${timestamp}")) {
                url = url.replace("${timestamp}", System.currentTimeMillis() + "");
            }

            if (url.contains("${token}")) {
                url = url.replace("${token}", DevicesUtils.getToken());
            }

            if (url.contains("${passportId}")) {
                url = url.replace("${passportId}", SharedPreferencesUtils.getInstance().getString(UserInfoConstants.passport_id, ""));
            }

            downloadBoring.loadUrl(url);
        }

    }

    @Override
    public void initData() {

    }


    /**
     * 打开本地图片
     */
    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }


    @Override
    public void initEvent() {
        ClickUtils.setFastOnClickListener(webShareView, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断微信是否安装
                if (!CommonUtils.isWeixinAvilible(MainApplication.getContext())) {
                    Toast.makeText(MineWebViewActivity.this, "微信未安装，请先安装微信", Toast.LENGTH_SHORT).show();
                    return;
                }
                /**
                 * webUrl 网页url
                 * webTitle 网页标题
                 * webDescription 网页描述
                 * openId
                 */

                String openId = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_openId, null);
                WXShareUtils.wxShareH5(openId, url, title, title);
            }
        });
        webBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (downloadBoring.canGoBack()) {
                    downloadBoring.goBack();
                } else {
                    finish();
                }
            }
        });

//        webClose.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });

//        webClose.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });

//        downloadBoring.setWebViewClient(new WebViewClient(){
//            @Override
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                super.onPageStarted(view, url, favicon);
//            }
//
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//                if (customeDialog.isShowing()){
//                    customeDialog.cancel();
//                }
//            }
//        });


    }


    private class ArticleWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //重置webview中img标签的图片大小
            imgReset();
//            view.loadUrl("javascript:window.WebJavascriptInterface.getSource('<head>'+" +
//                    "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
            LoadingUtils.getLoadingUtils(MineWebViewActivity.this).dismissLoading();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LoadingUtils.getLoadingUtils(MineWebViewActivity.this).showLoading();

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            ALog.e("customerWeb", "shouldOverrideUrlLoading:" + url);
            telNumberStr = "";
            if (url.startsWith("com.patient.scheme:jumpToTelephone?tel=")) {
                telNumberStr = url.replace("com.patient.scheme:jumpToTelephone?tel=", "");
                if (!TextUtils.isEmpty(telNumberStr)) {
                    openPhoneView(telNumberStr);
                }
            } else if (url.startsWith("com.patient.scheme")) {
                PushMessageUtil.getInstance().dealMessage(MineWebViewActivity.this, url);
            } else {
                view.loadUrl(url);
            }
//            webClose.setVisibility(View.VISIBLE);
            return true;
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            ALog.e("WebView Error Log:", error.getErrorCode() + "==" + error.getDescription());
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            ALog.e("WebView Error Log:", errorResponse.getStatusCode() + "");
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            ALog.e("WebView Error Log:", errorCode + "" + description);
        }


        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            ALog.e("WebView Error Log:", error.getPrimaryError() + "" + error.getUrl());
        }
    }

    private String telNumberStr = "";

    private void openPhoneView(String telNumberStr) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissionArray = new String[]{Manifest.permission.CALL_PHONE};
            boolean permissionPhone = PermissionChecker.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PermissionChecker.PERMISSION_GRANTED;
            if (!permissionPhone) {
                requestPermissions(permissionArray, 2001);
            } else {
                gotoOpenTel(telNumberStr);
            }
        } else {
            gotoOpenTel(telNumberStr);
        }
    }

    private void gotoOpenTel(@NonNull String tel) {

        ArrayList<String> tels = new ArrayList<>();
        tels.add(tel);

        AppReactUtils.INSTANCE.openPhoneView(this, tels);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ALog.e("customerWeb", "onActivityResult:" + requestCode + " " + resultCode);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) {
                return;
            }
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();

            ALog.e("customerWeb", "onActivityResult1111:" + result);
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }


    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) {
            return;
        }
        Uri[] results = null;

        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                ALog.e("customerWeb", "onActivityResult222");
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                ALog.e("customerWeb", "onActivityResult333:" + dataString);
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ALog.e("customerWeb", "onActivityResult555:" + i);
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                        ALog.e("customerWeb", "onActivityResult444:" + item.getUri());
                    }
                }
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2001) {
            boolean isCallGranted = false;
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                if (Manifest.permission.CALL_PHONE.equals(permission) && grantResults[i] == PermissionChecker.PERMISSION_GRANTED) {
                    isCallGranted = true;
                    break;
                }
            }
            if (!isCallGranted) {
                ToastUtils.showShort("请在手机设置中，开启拨打电话权限！");
            } else {
                gotoOpenTel(telNumberStr);
            }
        }
    }

    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     **/
    private void imgReset() {
        downloadBoring.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                "}" +
                "})()");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (downloadBoring.canGoBack()) {
                downloadBoring.goBack();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onRestart() {
//        if (!isNotReloadOnRestart) {
//            downloadBoring.reload();
//        }
        super.onRestart();
    }
}


